<?php

//    (c) 2011 Donders Centre/Simon Oosthoek
//
//    This file is part of PIM.
//
//    PIM is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 2 of the License, or
//    (at your option) any later version.
//
//    PIM is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with PIM.  If not, see <http://www.gnu.org/licenses/>.
//
include('header.tp');

#read in common pim functions:
require('pimfunctions.php');

ini_set('error_reporting', E_ALL);
error_reporting(E_ERROR | E_WARNING | E_PARSE);

#global variable fullname to convert username to full names
$fullname=projectdb_getnames();

/* ============================================================*/
/* start of main code                                          */
/* ============================================================*/

/* ---------------- handle input arguments -------------------- */
if (isset($_GET['host'])) {
	$qhost=$_GET['host'];
	$pidsonhost=glob($pim_datadir . "/$qhost" . "_*");
}
if (isset($_GET['pid'])) {
	$qpid=$_GET['pid'];
}
if (isset($_GET['pidfile'])) {
	//$pidfile=$pim_datadir . "/" . $_GET['pidfile'];
	list($qhost,$qpid) = explode("_", $_GET['pidfile']);
}
if (isset($_GET['user'])) {
	$quser=$_GET['user'];
}

/* ----------------- determine which output to show ------------ */
if ( strlen($qhost) > 1 && strlen($qpid) > 1 ) {
	// give information for this process
	show_host_pid($pim_datadir . "/" .$qhost . "_" . $qpid);
} else if (  strlen($qhost) > 1 && strlen($quser) > 1 ) {
	// show info about processes of $quser on $qhost
	show_host_user($pidsonhost, $qhost, $quser);
} else if ( strlen($qhost) > 1 ) {
	// show info about all processes on $qhost
	show_host($qhost);
} else if ( strlen($quser) > 1 ) {
	// show info about all processes for $quser
	show_user($quser);
} else {
	// show overview of all mentats and processes on them (with links)
	$allpids=glob($pim_datadir . "/men*_[0-9]*");
	show_cluster($allpids);
}

/* ============================================================*/
/* start of function definitions                               */
/* ============================================================*/

function show_host_pid ($pidfile) {
	global $pim_datadir;
	global $pim_actdir;
	global $fullname;
	$datafilenm = $pidfile;
	list($host,$pid)=explode("_", basename($pidfile));
	echo '<h1><a href="' . pim_link() . '">';
	echo '<img style="vertical-align:text-top" src="img/pim-logo.png" alt="PIM logo"/></a>';
	echo "Process information on " . fancy_host_link($host) . "</h1>\n";
	if (file_exists($datafilenm) ) {
		$data = pid_data($datafilenm);
		if (file_exists("$pim_actdir/" . basename($pidfile)) ) {
			$useract = pid_data("$pim_actdir/" . basename($pidfile));
		} 
			
		// print username if known
		$user = $data['header']['pid_owner'];
		echo "<p>info about process $pid on $host for ";
		echo fancy_user_link($data['header']['pid_owner']);
		echo "</a><br>\n";
		echo "<em>commandline: </em>";
		echo "<tt>" .  $data['header']['pid_cmdline'] ."</tt>";
		echo "</p>\n";		

		change_title("PIM: process $pid on $host for " .$data['header']['pid_owner']);

		$vsize=array();
		$pcpu=array();
		
		$basestamp=0;
		foreach($data['samples'] as $row) {
			if ($basestamp == 0) {
				$basestamp=$row['timestamp'];
			}
			//time in hrs from start
			$fromstart= round(($row['timestamp']-$basestamp) / 3600); 
			// mem in GB	
			$vsize[] = array($fromstart, $row['pid_vsize']/(1024*1024)); 
			$pcpu[] = array($fromstart, round($row['pid_pcpu'])); 
		}
?>
<h3>Plot of memory and cpu use over time</h3>
<p>NB: plot based on samples one hour apart</p>
<div id="processplot" style="width:600px;height:300px;"></div>

<script id="source" language="javascript" type="text/javascript">

//configure flot options       
var options = {
	xaxis: {
		// plot hours
		tickSize:24,
		tickDecimals:0
	},
	yaxis: {
		// memory in GB
		tickDecimals:0,
		tickSize:1
	},
	y2axes: {
		// cpu use in %
		ticks: [0,10,20,30,40,50,60,70,80,90,100],
		min: 0,
		max: 100
	}
	
};   
     
$(document).ready(function(){
      //plot the graph
      jQuery(function () {
        jQuery.plot(jQuery("#processplot"),  [ 
		{
<?php
echo "data: "  . __json_encode($vsize). ",\n";
?>
			lines: {show: true, fill: true},
			label: "<-- memory used (GB)"
		},
		{
<?php
echo "data: "  . __json_encode($pcpu) .",\n";
?>
			bars: {show: true},
			label: "cpu used (%) -->",
			yaxis: 2
		}
		], options);
      });
});
</script>

<?php
		echo "<h2>info about this process</h2>\n";
		echo "<table border=1 cellpadding=3>\n";
		if (isset( $data['header']['pid_starttime'])) {
			print_tr2("process started" ,strftime("%c", $data['header']['pid_starttime']));
		}
		print_tr2("Running for", elapsed_to_human($data['header']['pid_elapsedtime']));
		if (isset( $data['header']['pid_ownername'])) {
			print_tr2("process owner", $data['header']['pid_ownername']);
		}
		
		$usersgroups=exec("id -Gn " .  $data['header']['pid_owner']);
		//test to see whether user is under PIM control:
		// start with check if user is member of groups in $only_for_groups
		$userinclude = preg_match("/" . $data['config']['only_for_groups'] . "/", $usersgroups);
		// OR is member of the list of included users
		$userinclude = $userinclude || isset($data['config']['only_for_users']) && 
			(strpos($data['config']['only_for_users'], $data['header']['pid_owner']) > 0);
		// BUT not part of the list of $users_ignore
		$userinclude = $userinclude && 	!( isset( $data['config']['users_ignore']) &&
			  (strpos( $data['config']['users_ignore'], $data['header']['pid_owner'] > 0) ) );
		if ($userinclude) {
			print_tr1in2("Process under PIM management");
		} else {
			print_tr1in2("Process <b>NOT</b> under PIM management");
		}

		if (exclude_user($data['header']['pid_owner'])) {
			print_tr1in2("User temporarily excluded or on vacation");
		} else {
			
			if (isset( $data['notify']['pid_notified'])) {
					print_tr2("Last Notification sent", strftime("%c", $data['notify']['pid_notified']));
			}
			$pidrenewed= isset( $data['shellview']['pid_renewed'] ) ? $data['shellview']['pid_renewed'] : 0;
			if ($pidrenewed > 0 ) {
				if ( isset($data['shellview']['pid_renewed_human']) ) {
					print_tr2("Last Renewed by user", $data['shellview']['pid_renewed_human']);
				} else {
					print_tr2("Last Renewed by user",  strftime("%c", $pidrenewed));
				}
			}
			$urenew=isset( $useract['shellview']['user_renew']) ? $useract['shellview']['user_renew'] : 0;
			$ukill=isset( $useract['shellview']['user_kill']) ? $useract['shellview']['user_kill'] : 0;
			if ( $ukill > 0 || ($urenew > $pidrenewed) ) {
				print_tr1in2("User action pending");
			}

			if ($ukill > $urenew) {
				# print user requested kill
				print_tr2("user requested kill", strftime("%c", $ukill));
			} elseif ($urenew > $pidrenewed) {
				# print user requested renew
				print_tr2("user requested renew", strftime("%c", $urenew));
			}
		}


		echo "</table>\n";


	} else {
		print "<p>File $datafilenm could not be opened. Process probably doesn't exist anymore.</p>\n";
	}
}

function print_tr2($col1="", $col2="") {
	echo "<tr>";
	echo "<td valign=top>$col1</td>\n";
	echo "<td>$col2";
	echo "</td></tr>\n";
}

function print_tr1in2($col1="") {
	echo "<tr>";
	echo "<td colspan=\"2\" valign=top>$col1</td>\n";
	echo "</tr>\n";
}

function show_host_user ($pidfiles, $host, $user) {
	global $pim_datadir;
	echo '<h1><a href="' . pim_link() . '">';
	echo '<img style="vertical-align:text-top" src="img/pim-logo.png" alt="PIM logo"/></a>';
	echo ' <a href="' . pim_link() . '">PIM</a></h1>';
	echo '<h2>processes for '. fancy_user_link($user) . ' on ' . fancy_host_link($host) . "</h2>";

	change_title("PIM: processes for $user on $host");
	foreach ($pidfiles as $filenm) {
		$basenm=basename($filenm);
		if ( file_exists($pim_datadir . "/" . $user . "_" . $basenm) ) {
			list($host,$pid) = explode ("_", $basenm);
			echo "<p><a href=\"" . process_link($host,$pid) . "\">$pid (" .  get_proctype($host, $pid) .")</a></p>";
		}
	}
}

function show_host ($host) {
	global $pim_datadir;
	echo '<h1><a href="' . pim_link() . '">';
	echo '<img style="vertical-align:text-top" src="img/pim-logo.png" alt="PIM logo"/>';
	echo ' <a href="' . pim_link() . '">PIM</a></h1>';
	echo "<h2>processes on " . fancy_host_link($host)."</h2>";
	change_title("PIM: processes on $host");
	$pidfiles=glob($pim_datadir . "/*_$host*");
	foreach($pidfiles as $file) {
		$basenames[]=basename($file);
	}
	asort($basenames);
	foreach ($basenames as $basenm) {
		list($user,$host,$pid) = explode ("_", $basenm);
		$url=process_link($host,$pid);
		$userurl=user_link($user);
		if (file_exists("$pim_datadir/${host}_${pid}")) {
			echo "<p><b><a href=\"$url\">" . get_proctype($host, $pid). "</b>: $pid</a> for " . fancy_user_link($user) .'</p>';
		}
	}
}

function show_user ($user) {
	global $pim_datadir;
	global $fullname;
	echo '<h1><a href="' . pim_link() . '">';
	echo '<img style="vertical-align:text-top" src="img/pim-logo.png" alt="PIM logo"/>';
	echo ' <a href="' . pim_link() . '">PIM</a></h1>';
	echo "<h2>processes for ". fancy_user_link($user) . "</h2>";
	echo "<p><img width='108px' height='108px' border=\"0\"";
	echo "src=\"http://projects.fcdonders.nl/app/webroot/img/staff/thumbs-intranet/$user.jpg\" ";
	echo "alt=\"Photo for user $fullname[$user]\"></a>\n";
	echo "</p>\n";
	change_title("PIM: processes for $user");
	$pidfiles = glob("$pim_datadir/$user" . "_*");
	foreach($pidfiles as $file) {
		$basenames[]=basename($file);
	}
	asort($basenames);
	$count=0;
	$curhost="";
	foreach ($basenames as $basenm) {
		list($usrnm,$host,$pid) = explode ("_", $basenm);
		if ($curhost != $host) {
			$curhost=$host;
			echo "<h3>" . fancy_host_link($curhost) . "</h3>\n";
		}
		echo "<ul>\n";
		if ( file_exists( "$pim_datadir/${host}_$pid" ) ) {
			$url=process_link($host,$pid);
			$hosturl=host_link($host);
			echo "<li><a href=\"$url\">$pid</a>  (" . get_proctype($host, $pid) .")</li>";
			$count++;
		//} else {
		//	echo "<li>defunct index file $basenm</li>\n";
		}
		echo "</ul>\n";
	}
	if ($count == 0) {
		echo "<p>no pids known for user $user</p>\n";
	}
}

function show_cluster ($pidfiles) {
	global $pim_datadir;
	global $fullname;
	?>
	<h1><img style="vertical-align:text-top" src="img/pim-logo.png" alt="PIM logo"/>
	Process Information on Mentat cluster</h1>
	<?php
	
	// get all the data file information in a few arrays:
	foreach ($pidfiles as $filenm) {
		$basenm=basename($filenm);
		$arrayofone=glob($pim_datadir . "/*_" . $basenm);
		list($user,$host,$pid) = explode ("_", basename($arrayofone[0]));
		$url=process_link($host,$pid);
		$data['by-user'][$user][$host][]=$pid;
		$data['by-host'][$host][$user][]=$pid;
		$users[$user]=$user;
		$hosts[$host]=$host;
	}
	?>
	<div id="tabs">
	
	<ul>
	<li><a href="#tabs-1">By User</a></li>
	<li><a href="#tabs-2">By Host</a></li>
	<li><a href="#tabs-3">Help</a></li>
	<li><a href="#tabs-4">FAQ</a></li>
	</ul>
	
	<div id="tabs-1">
	
	<table>

	<?php
	asort($users);

	foreach ($users as $user) {
		$url=user_link($user);
		$imgurl=projectdb_img($user);
		echo "<tr>";
		echo "<td valign=top><a href=\"$url\">" ;
		echo "<img width='108px' height='108px' border=\"0\" src=\"$imgurl\" alt=\"Photo $user\"></a>\n";
		echo "<br>" .fancy_user_link($user). "</td>\n";

		echo "<td valign=\"top\">\n<ul>";
		foreach ($data['by-user'][$user] as $hn => $pids) {
			$url=host_link($hn);
			echo "<li><a href=\"$url\">$hn</a>";
			$pidcount=0;
			foreach ($pids as $pid) {
				$pidcount++;
			}
			$pstring = $pidcount> 1? "processes" : "process";
			echo " ($pidcount $pstring)\n";
			echo "</li>\n";
		}
		echo "</ul>\n";
		echo "</td></tr>\n";
	}
	?>

	</table>

	
	</div> <!-- tabs-1 -->

	<div id="tabs-2">
	<?php

	asort($hosts);
	foreach ($hosts as $host) {
		$url=host_link($host);
		echo "<h2>" . fancy_host_link($host) . "</h2>";
		echo "<ul>\n";
		ksort($data['by-host'][$host]);
		foreach ($data['by-host'][$host] as $un => $pids) {
			echo "<li>". fancy_user_link($un);
			$pidcount=0;
			foreach ($pids as $pid) {
				$pidcount++;
			}
			$pstring = $pidcount> 1? "processes" : "process";
			echo " ($pidcount $pstring)\n";
			echo "</li>\n";
		}
		echo "</ul>\n\n";
	}
	?>
	</div> <!-- tabs-2 -->
	<div id="tabs-3">

		<p><a href="https://intranet.donders.ru.nl/index.php?id=3709">PIM Documentation on Intranet</a></p>
		
		<iframe src="https://intranet.donders.ru.nl/index.php?id=3709&type=98" width="100%" height="600">
			<p>Your browser does not support iframes.</p>
		</iframe>

	</div>
	<div id="tabs-4">
		<p><a href="https://intranet.donders.ru.nl/index.php?id=3753">FAQ for PIM</a></p>
		<iframe src="https://intranet.donders.ru.nl/index.php?id=3753&type=98" width="100%" height="600">
			<p>Your browser does not support iframes.</p>
		</iframe>

	</div>
	</div> <!-- tabs -->
<?php
}


include('footer.tp');
?>
